package com.hz.friends.chat;

import java.io.File;
import java.io.FileOutputStream;
import java.lang.reflect.Field;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.json.JSONException;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Paint.Join;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.provider.MediaStore;
import android.provider.MediaStore.Video.Thumbnails;
import android.provider.MediaStore.Video.VideoColumns;
import android.support.v4.view.ViewPager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.AVUtils;
import com.avos.avoscloud.GetCallback;
import com.easemob.chatuidemo.widget.ExpandGridView;
import com.easemob.chatuidemo.widget.PasteEditText;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.hisun.phone.core.voice.model.im.IMTextMsg;
import com.hisun.phone.core.voice.util.Log4Util;
import com.hz.friends.activity.BaseActivity;
import com.hz.friends.activity.R;
import com.hz.friends.activity.UserInfosActivity;
import com.hz.friends.application.CustomApplication;
import com.hz.friends.chat.Helper.CCPIntentUtils;
import com.hz.friends.chat.entity.IMChatMessage;
import com.hz.friends.db.DBContactUser;
import com.hz.friends.db.DBMessageManager;
import com.hz.friends.global.Global;
import com.hz.friends.group.CreateGroupActivity;
import com.hz.friends.serverrequest.ALCCPEngine;
import com.hz.friends.serverrequest.ALEngineConfig.CallBack;
import com.hz.friends.sound.SoundMeter;
import com.hz.friends.utils.DensityUtil;
import com.hz.friends.utils.MLog;
import com.hz.friends.utils.UtilTools;

public class GroupChatActivity extends BaseChatActivity implements
		OnClickListener {

	private PullToRefreshListView mlist;
	private RelativeLayout layout_recording;
	private ImageView imv_recordtips;
	private TextView txv_recordtips;
	private PasteEditText edt_message;
	private ViewPager mviewpager;
	private LinearLayout layout_more;
	private Button btn_voice;
	private Button btn_keyboard;
	private TextView txv_presstospeak;
	private RelativeLayout layout_btncontainer;
	private ImageButton imbtn_emoticons;
	private Button btn_morefuction;
	private List<String> reslist;
	private Button btn_sendmsg;
	private MessageAdpter msgadpter;
	private WakeLock wakeLock;
	private SoundMeter mSensor;
	private Drawable[] micImages;
	private boolean isGroup = false;
	private final int VIDEO_CAPTURE = 0;
	private final int PHOTO_REQUEST_GALLERY = 1;
	private final int PHOTO_REQUEST_CAMERA = 2;
	private int pageindex = 0;// 查询单聊历史记录分页
	private int grouplimit = 20;
	private Date groupdate = new Date();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_singlechat);
		init();
		initbarView();
		initViews();
		initEvents();
		initEmotions();
		setViews();
	}

	private void initbarView() {
		ImageButton imbtn_bar_left = (ImageButton) findViewById(R.id.imbtn_bar_left); // bar
		imbtn_bar_left.setOnClickListener(this);
		imbtn_bar_left.setVisibility(View.VISIBLE); // 左边按钮
		ImageButton imbtn_bar_right = (ImageButton) findViewById(R.id.imbtn_bar_right); // bar
																						// 右边按钮
		TextView imbtn_bar_title = (TextView) findViewById(R.id.imbtn_bar_title); // bar
		imbtn_bar_left.setImageResource(R.drawable.ic_leftback_arrow);
		imbtn_bar_title.setText(getIntent().getStringExtra("titlename"));
		imbtn_bar_right.setOnClickListener(this);
	}

	@Override
	protected void init() {
		reslist = getExpressionRes(54);
		// 动画资源文件,用于录制语音时
		micImages = new Drawable[] {
				getResources().getDrawable(R.drawable.record_animate_01),
				getResources().getDrawable(R.drawable.record_animate_02),
				getResources().getDrawable(R.drawable.record_animate_03),
				getResources().getDrawable(R.drawable.record_animate_04),
				getResources().getDrawable(R.drawable.record_animate_05),
				getResources().getDrawable(R.drawable.record_animate_06),
				getResources().getDrawable(R.drawable.record_animate_07),
				getResources().getDrawable(R.drawable.record_animate_08),
				getResources().getDrawable(R.drawable.record_animate_09),
				getResources().getDrawable(R.drawable.record_animate_10),
				getResources().getDrawable(R.drawable.record_animate_11),
				getResources().getDrawable(R.drawable.record_animate_12),
				getResources().getDrawable(R.drawable.record_animate_13),
				getResources().getDrawable(R.drawable.record_animate_14), };

		isGroup = getIntent().getBooleanExtra("isGroup", false);
		enterGroup();
	}

	@Override
	protected void initViews() {
		mlist = (PullToRefreshListView) findViewById(R.id.mlistview); // listview
		mlist.setMode(Mode.PULL_FROM_START);

		layout_recording = (RelativeLayout) findViewById(R.id.layout_recording); // 录音提示布局
		imv_recordtips = (ImageView) findViewById(R.id.imv_recordtips); // 录音提示图片
		txv_recordtips = (TextView) findViewById(R.id.txv_recordtips); // 录音提示
		txv_recordtips = (TextView) findViewById(R.id.txv_recordtips); // 录音提示
		btn_voice = (Button) findViewById(R.id.btn_voice); // 录音按钮
		btn_keyboard = (Button) findViewById(R.id.btn_keyboard); // 键盘输入按钮
		txv_presstospeak = (TextView) findViewById(R.id.txv_presstospeak); // 按住说话
		edt_message = (PasteEditText) findViewById(R.id.edt_message); // 信息输入框
		imbtn_emoticons = (ImageButton) findViewById(R.id.imbtn_emoticons); // 表情按钮
		btn_morefuction = (Button) findViewById(R.id.btn_morefuction); // 更多功能
		btn_sendmsg = (Button) findViewById(R.id.btn_sendmsg); // 发送消息
		layout_more = (LinearLayout) findViewById(R.id.layout_more); // 表情选择、拍照、游戏等更多功能布局
		mviewpager = (ViewPager) findViewById(R.id.mviewpager); // 表情viewpage
		layout_btncontainer = (RelativeLayout) findViewById(R.id.layout_btncontainer); // 布局包含拍照、游戏、等功能
		// LinearLayout layout_fromphoto = (LinearLayout)
		// findViewById(R.id.layout_fromphoto); // 从相册选择
		// LinearLayout layout_takephone = (LinearLayout)
		// findViewById(R.id.layout_takephone); // 拍照
		// LinearLayout layout_takevoide = (LinearLayout)
		// findViewById(R.id.layout_takevoide); // 录制视频
		// LinearLayout layout_game = (LinearLayout)
		// findViewById(R.id.layout_game); // 游戏
		ImageButton imbtn_fromphoto = (ImageButton) findViewById(R.id.imbtn_fromphoto); // 从相册选择
		ImageButton imbtn_takephone = (ImageButton) findViewById(R.id.imbtn_takephone); // 拍照
		ImageButton imbtn_takevoide = (ImageButton) findViewById(R.id.imbtn_takevoide); // 录制视频
		ImageButton imbtn_game = (ImageButton) findViewById(R.id.imbtn_game); // 游戏

		btn_voice.setOnClickListener(this);
		btn_keyboard.setOnClickListener(this);
		txv_presstospeak.setOnClickListener(this);
		edt_message.setOnClickListener(this);
		btn_morefuction.setOnClickListener(this);
		imbtn_emoticons.setOnClickListener(this);
		imbtn_fromphoto.setOnClickListener(this);
		imbtn_takephone.setOnClickListener(this);
		imbtn_takevoide.setOnClickListener(this);
		imbtn_game.setOnClickListener(this);

		registerForContextMenu(mlist); // listview上下文菜单

	}

	@Override
	protected void setViews() {
		wakeLock = ((PowerManager) getSystemService(Context.POWER_SERVICE))
				.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "demo");
		mSensor = new SoundMeter();
		msgadpter = new MessageAdpter(this);
		mlist.setAdapter(msgadpter);
		// 单聊窗口获取首次显示信息
		if (!isGroup)
			msgadpter.getFirstData(CustomApplication.getInstance().user
					.getObjectId());
	}

	/**
	 * 初始化表情
	 */
	private void initEmotions() {
		// 初始化表情viewpager
		List<View> views = new ArrayList<View>();
		View gv1 = getGridChildView(1);
		View gv2 = getGridChildView(2);
		views.add(gv1);
		views.add(gv2);
		mviewpager.setAdapter(new ExpressionPagerAdapter(views));
	}

	@Override
	protected void initEvents() {
		edt_message.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {

				if (s.length() > 0) {
					btn_sendmsg.setVisibility(View.VISIBLE);
					btn_morefuction.setVisibility(View.GONE);
				} else {
					btn_morefuction.setVisibility(View.VISIBLE);
					btn_sendmsg.setVisibility(View.GONE);
				}

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub

			}
		});

		btn_sendmsg.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				String messagetxt = edt_message.getText().toString().trim();
				if (messagetxt.length() == 0)
					return;
				if (isGroup) {
					msgadpter.sendMessage(messagetxt,
							CustomApplication.getInstance().currgroup);
				} else {
					msgadpter.sendMessage(messagetxt,
							CustomApplication.getInstance().user);
				}
				edt_message.setText("");
				mlist.getRefreshableView().setSelection(msgadpter.getCount());
				// IMChatMessage immsg = new IMChatMessage();
				// immsg.setMessageContent(messagetxt);
				// immsg.setImState(IMChatMessage.MessageDirect.RECEIVE);
				// immsg.setMessageType(IMChatMessage.MessageType.TXT);
				// immsg.setMessagetime(new Date());
				// immsg.setMessageId(System.currentTimeMillis()+"");
				// immsg.setUser(AVUser.getCurrentUser());
				// msgadpter.addData(immsg);
				// msgadpter.notifyDataSetChanged();
				// edt_message.setText("");

			}
		});

		txv_presstospeak.setOnTouchListener(new PressToSpeakListen());
		mlist.setOnRefreshListener(new OnRefreshListener2<ListView>() {

			@Override
			public void onPullUpToRefresh(
					PullToRefreshBase<ListView> refreshView) {

			}

			@Override
			public void onPullDownToRefresh(
					PullToRefreshBase<ListView> refreshView) {
				if (!isGroup) {
					int count = msgadpter.getBeforeMessages(
							CustomApplication.getInstance().user.getObjectId(),
							pageindex);
					mHandler.post(new Runnable() {

						@Override
						public void run() {
							mlist.onRefreshComplete();
						}
					});
					if (count == 0) {
						mlist.setMode(Mode.DISABLED);
					}
				} else {
					ALCCPEngine.defauleEngine().getMessageOfChat(
							CustomApplication.getInstance().currgroup,
							grouplimit, groupdate, new CallBack() {

								@Override
								public void done(Object object,
										AVException avexception) {
									mlist.onRefreshComplete();
									if (avexception == null) {
										List<AVObject> list = (List<AVObject>) object;
										if (list != null && list.size() > 0) {
											for (int i = 0; i < list.size(); i++) {
												AVObject obj = list.get(i);
												msgadpter.reciveMessage(obj);
											}
											msgadpter.notifyDataSetChanged();
											groupdate = list.get(0)
													.getCreatedAt();
										} else {
											mlist.setMode(Mode.DISABLED);
										}

									} else {
										avexception.printStackTrace();
										showToast("加载失败");
									}

								}
							});
				}
			}
		});
		mlist.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View view,
					int position, long id) {
				msgadpter.setLongclickindex(position - 1);
				return false;
			}
		});

	}

	/**
	 * 获取表情的gridview的子view
	 * 
	 * @param i
	 * @return
	 */
	private View getGridChildView(int i) {
		View view = View.inflate(this, R.layout.expression_gridview, null);
		// ExpandGridView gv = (ExpandGridView)
		// view.findViewById(R.id.gridview);
		GridView gv = (GridView) view.findViewById(R.id.gridview);
		List<String> list = new ArrayList<String>();
		if (i == 1) {
			List<String> list1 = reslist.subList(0, 27);
			list.addAll(list1);
		} else if (i == 2) {
			list.addAll(reslist.subList(27, reslist.size()));
		}
		list.add("delete_expression");
		final ExpressionAdapter expressionAdapter = new ExpressionAdapter(this,
				1, list);
		gv.setAdapter(expressionAdapter);
		setGridViewHeightBasedOnChildren(gv);
		gv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				String filename = expressionAdapter.getItem(position);
				try {
					// 文字输入框可见时，才可输入表情
					// 按住说话可见，不让输入表情
					if (btn_keyboard.getVisibility() != View.VISIBLE) {

						if (filename != "delete_expression") { // 不是删除键，显示表情
							Class clz = Class
									.forName("com.hz.friends.chat.SmileUtils");
							Field field = clz.getField(filename);
							edt_message.append(SmileUtils.getSmiledText(
									GroupChatActivity.this,
									(String) field.get(null)));

						} else { // 删除文字或者表情
							if (!TextUtils.isEmpty(edt_message.getText())) {

								int selectionStart = edt_message
										.getSelectionStart();// 获取光标的位置
								if (selectionStart > 0) {
									String body = edt_message.getText()
											.toString();
									String tempStr = body.substring(0,
											selectionStart);
									int i = tempStr.lastIndexOf("[");// 获取最后一个表情的位置
									if (i != -1) {
										CharSequence cs = tempStr.substring(i,
												selectionStart);
										if (SmileUtils.containsKey(cs
												.toString()))
											edt_message.getEditableText()
													.delete(i, selectionStart);
										else
											edt_message.getEditableText()
													.delete(selectionStart - 1,
															selectionStart);
									} else {
										edt_message.getEditableText().delete(
												selectionStart - 1,
												selectionStart);
									}
								}
							}

						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				}

			}
		});
		return view;
	}

	public List<String> getExpressionRes(int getSum) {
		List<String> reslist = new ArrayList<String>();
		for (int x = 1; x <= getSum; x++) {
			DecimalFormat dft = new DecimalFormat("000");
			String filename = "ee_" + dft.format(x);

			reslist.add(filename);

		}
		return reslist;

	}

	private String tempphotopath = null;

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.imbtn_bar_left:
			finish();
			break;
		case R.id.imbtn_bar_right:
			mlist.showContextMenu();

			// if (isGroup) {
			// Intent groupintent = new Intent(this, CreateGroupActivity.class);
			// groupintent.putExtra("activitytype", 2);
			// startActivity(groupintent);
			// } else {
			// Intent groupintent = new Intent(this, UserInfosActivity.class);
			// startActivity(groupintent);
			// }
			break;
		case R.id.btn_voice: // 显示录音
			hideKeyboard();
			layout_more.setVisibility(View.GONE);
			btn_voice.setVisibility(View.GONE);
			edt_message.setVisibility(View.GONE);
			btn_keyboard.setVisibility(View.VISIBLE);
			txv_presstospeak.setVisibility(View.VISIBLE);
			break;
		case R.id.btn_keyboard: // 显示输入
			edt_message.requestFocus();
			// showKeyboard();
			layout_more.setVisibility(View.GONE);
			btn_voice.setVisibility(View.VISIBLE);
			edt_message.setVisibility(View.VISIBLE);
			btn_keyboard.setVisibility(View.GONE);
			txv_presstospeak.setVisibility(View.GONE);
			break;
		case R.id.btn_morefuction:// 更多
			if (btn_morefuction.getTag() == null) {
				hideKeyboard();
				mHandler.postDelayed(new Runnable() {

					@Override
					public void run() {
						layout_more.setVisibility(View.VISIBLE);
						layout_btncontainer.setVisibility(View.VISIBLE);
						mviewpager.setVisibility(View.GONE);
						btn_morefuction.setTag("1");
						imbtn_emoticons.setTag(null);
					}
				}, 100);

			} else {
				// showKeyboard();
				layout_more.setVisibility(View.GONE);
				btn_morefuction.setTag(null);
			}

			break;
		case R.id.imbtn_emoticons:// 表情输入
			if (imbtn_emoticons.getTag() == null) {
				hideKeyboard();
				if (btn_voice.getVisibility() != View.VISIBLE) {
					btn_voice.setVisibility(View.VISIBLE);
					edt_message.setVisibility(View.VISIBLE);
					btn_keyboard.setVisibility(View.GONE);
					txv_presstospeak.setVisibility(View.GONE);
				}

				mHandler.postDelayed(new Runnable() {

					@Override
					public void run() {
						layout_more.setVisibility(View.VISIBLE);
						layout_btncontainer.setVisibility(View.GONE);
						mviewpager.setVisibility(View.VISIBLE);
						imbtn_emoticons.setTag("1");
						btn_morefuction.setTag(null);
					}
				}, 100);

			} else {
				showKeyboard();
				layout_more.setVisibility(View.GONE);
				imbtn_emoticons.setTag(null);
			}

			break;
		case R.id.txv_presstospeak:// 录音
			break;
		case R.id.edt_message:// 输入框点击
			if (layout_more.getVisibility() == View.VISIBLE) {
				layout_more.setVisibility(View.GONE);
				layout_btncontainer.setVisibility(View.GONE);
				return;
			}
			showKeyboard();

			break;
		case R.id.imbtn_fromphoto:// 从相册
			if (!android.os.Environment.MEDIA_MOUNTED
					.equals(android.os.Environment.getExternalStorageState())) {
				showToast("sdcard不可用");
				return;
			}

			Intent intentfromphoto = new Intent(Intent.ACTION_PICK, null);
			intentfromphoto.setDataAndType(
					MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
			startActivityForResult(intentfromphoto, PHOTO_REQUEST_GALLERY);

			break;
		case R.id.imbtn_takephone:// 拍照
			if (!android.os.Environment.MEDIA_MOUNTED
					.equals(android.os.Environment.getExternalStorageState())) {
				showToast("sdcard不可用");
				return;
			}
			try {
				Intent intenttakephone = new Intent(
						MediaStore.ACTION_IMAGE_CAPTURE);
				// 临时文件
				String photodir = Environment.getExternalStorageDirectory()
						+ "/" + Global.productName + "/Image/";
				String photopath = photodir + System.currentTimeMillis()
						+ ".jpg";
				File filedir = new File(photodir);
				File file = new File(photopath);
				if (!filedir.exists())
					filedir.mkdirs();
				if (!filedir.exists())
					file.createNewFile();
				// intenttakephone.putExtra(MediaStore.EXTRA_OUTPUT,
				// Uri.fromFile(file));
				// intenttakephone.putExtra(MediaStore.Images.Media.ORIENTATION,
				// 0);
				startActivityForResult(intenttakephone, PHOTO_REQUEST_CAMERA);
				tempphotopath = photopath;
			} catch (Exception e) {
				e.printStackTrace();
			}

			break;
		case R.id.imbtn_takevoide:// 录制视频
			if (!android.os.Environment.MEDIA_MOUNTED
					.equals(android.os.Environment.getExternalStorageState())) {
				showToast("sdcard不可用");
				return;
			}
			Intent intentvoide = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
			intentvoide.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
			startActivityForResult(intentvoide, VIDEO_CAPTURE);
			break;
		default:
			break;
		}
	}

	/**
	 * 按住说话listener
	 * 
	 */
	class PressToSpeakListen implements View.OnTouchListener {

		private long startVoiceT;
		private String voiceName;
		private long endVoiceT;

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			switch (event.getAction()) {
			case MotionEvent.ACTION_DOWN:
				if (!Environment.getExternalStorageDirectory().exists()) {
					Toast.makeText(getApplicationContext(), "No SDCard",
							Toast.LENGTH_SHORT).show();
					return false;
				}
				v.setPressed(true);
				layout_recording.setVisibility(View.VISIBLE);
				txv_recordtips.setText("手指上滑，取消发送");
				txv_recordtips.setBackgroundColor(Color.TRANSPARENT);
				startVoiceT = System.currentTimeMillis();
				voiceName = startVoiceT + ".amr";
				startRecord(voiceName);
				return true;
			case MotionEvent.ACTION_MOVE: {
				return true;
			}
			case MotionEvent.ACTION_UP:
				v.setPressed(false);
				layout_recording.setVisibility(View.INVISIBLE);
				if (event.getY() < 0) {
					stopRecord();
					// discard the recorded audio.
					File file = new File(mSensor.getVoiceDir() + voiceName);
					if (file.exists()) {
						file.delete();
					}
					mSensor.setName(null);
				} else {
					stopRecord();
					// endVoiceT = SystemClock.currentThreadTimeMillis();
					endVoiceT = System.currentTimeMillis();
					int time = (int) ((endVoiceT - startVoiceT) / 1000.0);
					if (time < 1) {
						Toast.makeText(getApplicationContext(), "录音时间太短", 0)
								.show();
					} else {
						// 发送语音
						if (isGroup) {
							msgadpter.sendVoiceMessage(mSensor.getVoicePath(),
									time,
									CustomApplication.getInstance().currgroup);
						} else {
							msgadpter.sendVoiceMessage(mSensor.getVoicePath(),
									time, CustomApplication.getInstance().user);
						}
						mlist.getRefreshableView().setSelection(
								msgadpter.getCount());

					}
				}
				return true;
			default:
				return false;
			}
		}

	}

	private Handler mHandler = new Handler() {
	};
	private static final int POLL_INTERVAL = 300;

	private Runnable mPollTask = new Runnable() {
		public void run() {
			double amp = mSensor.getAmplitude();
			updateDisplay(amp);
			mHandler.postDelayed(mPollTask, POLL_INTERVAL);

		}
	};

	// 开始录音
	private void startRecord(String name) {
		synchronized (mSensor) {
			mSensor.start(name);
			// mHandler.postDelayed(mPollTask, POLL_INTERVAL);
			final AnimationDrawable voiceAnimation = (AnimationDrawable) imv_recordtips
					.getDrawable();
			voiceAnimation.start();

		}

	}

	// 停止录音
	private void stopRecord() {
		synchronized (mSensor) {
			// mHandler.removeCallbacks(mSleepTask);
			// mHandler.removeCallbacks(mPollTask);
			mSensor.stop();
			// imv_recordtips.setImageDrawable(micImages[0]);
			final AnimationDrawable voiceAnimation = (AnimationDrawable) imv_recordtips
					.getDrawable();
			voiceAnimation.stop();

		}

	}

	protected void onReceiveBroadcast(Intent intent) {
		if (intent == null || intent.getExtras() == null)
			return;
		if (CCPIntentUtils.INTENT_IM_RECIVE.equals(intent.getAction())) {
			boolean misGroup = intent.getBooleanExtra("isGroup", false);
			String msgObjId = intent.getStringExtra("msgObjId");
			AVObject msgObj = AVObject.createWithoutData("MessageOfChat",
					msgObjId);
			if (isGroup && misGroup) {// 群消息
				msgObj.fetchIfNeededInBackground("fromUser,group",
						new GetCallback<AVObject>() {
							@Override
							public void done(AVObject obj, AVException e) {
								// TODO Auto-generated method stub
								if (obj != null && e == null) {
									MLog.i(TAG,
											"====收到消息:"
													+ obj.getJSONObject("userData"));
									msgadpter.reciveMessage(obj);
								}
								if (e != null)
									e.printStackTrace();
							}
						});

			}
			if (!isGroup && !misGroup) {// 单聊消息
				IMChatMessage message = (IMChatMessage) intent
						.getSerializableExtra("IMChatMessage");
				DBContactUser fromUser = message.getFromuser();
				if (fromUser == null
						|| !fromUser.getUserid().equals(
								CustomApplication.getInstance().user
										.getObjectId()))
					return;
				msgadpter.addData(message);
				msgadpter.notifyDataSetChanged();

				// msgObj.fetchIfNeededInBackground("fromUser,toUser", new
				// GetCallback<AVObject>() {
				//
				// @Override
				// public void done(AVObject obj, AVException e) {
				// if(e != null)
				// e.printStackTrace();
				// if (obj!=null && e==null)
				// {
				// MLog.i(TAG, "====收到消息:"+obj.getJSONObject("userData"));
				// AVUser fromUser = obj.getAVUser("fromUser");
				// if(fromUser == null ||
				// !fromUser.getObjectId().equals(CustomApplication.getInstance().user.getObjectId()))
				// return;
				// msgadpter.reciveMessage(obj);
				// }
				//
				// }
				// });
			}

		}
	}

	private void updateDisplay(double signalEMA) {

		// switch ((int) signalEMA) {
		// case 0:
		// case 1:
		// imv_recordtips.setImageDrawable(micImages[2]);
		// break;
		// case 2:
		// case 3:
		// imv_recordtips.setImageDrawable(micImages[4]);
		//
		// break;
		// case 4:
		// case 5:
		// imv_recordtips.setImageDrawable(micImages[6]);
		// break;
		// case 6:
		// case 7:
		// imv_recordtips.setImageDrawable(micImages[9]);
		// break;
		// case 8:
		// case 9:
		// imv_recordtips.setImageDrawable(micImages[11]);
		// break;
		// case 10:
		// case 11:
		// imv_recordtips.setImageDrawable(micImages[13]);
		// break;
		// default:
		// imv_recordtips.setImageDrawable(micImages[0]);
		//
		// break;
		// }
	}

	/**
	 * 隐藏软键盘
	 */
	public void hideKeyboard() {
		InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		if (inputMethodManager != null) {
			View localView = getCurrentFocus();
			if (localView != null && localView.getWindowToken() != null) {
				IBinder windowToken = localView.getWindowToken();
				inputMethodManager.hideSoftInputFromWindow(windowToken, 0);
			}
		}
	}

	/**
	 * 显示软键盘
	 */
	private void showKeyboard() {
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.showSoftInput(edt_message, InputMethodManager.SHOW_FORCED);
	}

	// 进入聊天室
	private void enterGroup() {
		if (!isGroup)
			return;
		ALCCPEngine.defauleEngine().enterGroup(
				CustomApplication.getInstance().currgroup, new CallBack() {

					@Override
					public void done(Object object, AVException avexception) {
						MLog.i(TAG, "-enterGroup---object:" + object
								+ " avexception:" + avexception);
						cancleWaitDialog();
						if (avexception == null) {// 进群成功

						} else {// 进群失败
							avexception.printStackTrace();
							new AlertDialog.Builder(GroupChatActivity.this)
									.setTitle("提示")
									.setMessage("进入聊天室失败,请重新尝试")
									.setPositiveButton(
											"确定",
											new DialogInterface.OnClickListener() {

												@Override
												public void onClick(
														DialogInterface dialog,
														int which) {
													dialog.dismiss();
													dialog.cancel();
													finish();
												}
											}).create().show();

						}
					}
				});
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		// 录制视频
		if (resultCode == Activity.RESULT_OK && requestCode == VIDEO_CAPTURE) {
			Uri uri = data.getData();
			Cursor cursor = this.getContentResolver().query(uri, null, null,
					null, null);
			if (cursor != null && cursor.moveToNext()) {
				int id = cursor.getInt(cursor.getColumnIndex(VideoColumns._ID));
				String filePath = cursor.getString(cursor
						.getColumnIndex(VideoColumns.DATA));
				int duration = cursor.getInt(cursor
						.getColumnIndex(MediaStore.Video.Media.DURATION));
				Bitmap bitmap = Thumbnails.getThumbnail(getContentResolver(),
						id, Thumbnails.MINI_KIND, null);
				cursor.close();

				if (isGroup)
					msgadpter.sendViodeMessage(filePath, duration, bitmap,
							CustomApplication.getInstance().currgroup);
				else
					msgadpter.sendViodeMessage(filePath, duration, bitmap,
							CustomApplication.getInstance().user);
				mlist.getRefreshableView().setSelection(msgadpter.getCount());

			}
		}
		// 相册返回图片
		if (resultCode == Activity.RESULT_OK
				&& requestCode == PHOTO_REQUEST_GALLERY) {
			if (data != null) {
				Uri uri = data.getData();
				String[] filePathColumn = { MediaStore.Images.Media.DATA,
						VideoColumns._ID };
				Cursor cursor = getContentResolver().query(uri, filePathColumn,
						null, null, null);
				cursor.moveToFirst();
				int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
				String picturePath = cursor.getString(columnIndex);
				int idIndex = cursor.getColumnIndex(filePathColumn[1]);
				int id = cursor.getInt(idIndex);
				Bitmap bitmap = android.provider.MediaStore.Images.Thumbnails
						.getThumbnail(getContentResolver(), id,
								Thumbnails.MINI_KIND, null);
				cursor.close();
				if (isGroup)
					msgadpter.sendPhotoMessage(picturePath, bitmap,
							CustomApplication.getInstance().currgroup);
				else
					msgadpter.sendPhotoMessage(picturePath, bitmap,
							CustomApplication.getInstance().user);
				mlist.getRefreshableView().setSelection(msgadpter.getCount());

			}
		}

		if (resultCode == Activity.RESULT_OK
				&& requestCode == PHOTO_REQUEST_CAMERA) {
			// if(tempphotopath != null){
			// if(isGroup)
			// msgadpter.sendPhotoMessage(tempphotopath,null,
			// CustomApplication.getInstance().currgroup);
			// else
			// msgadpter.sendPhotoMessage(tempphotopath,null,
			// CustomApplication.getInstance().user);
			// mlist.setSelection(msgadpter.getCount());
			// }

			if (data != null) {
				Bundle bundle = data.getExtras();
				// 拍照取消
				if (bundle == null)
					return;
				Bitmap bitmap = (Bitmap) bundle.get("data");
				File imagefile = saveMyBitmap(System.currentTimeMillis()
						+ ".jpg", bitmap);
				if (imagefile == null)
					return;
				if (isGroup)
					msgadpter.sendPhotoMessage(imagefile.getAbsolutePath(),
							null, CustomApplication.getInstance().currgroup);
				else
					msgadpter.sendPhotoMessage(imagefile.getAbsolutePath(),
							null, CustomApplication.getInstance().user);
				mlist.getRefreshableView().setSelection(msgadpter.getCount());
				imagefile = null;
				bitmap.recycle();

			}
		}

		super.onActivityResult(requestCode, resultCode, data);

	}

	public File saveMyBitmap(String name, Bitmap mBitmap) {
		if (!android.os.Environment.MEDIA_MOUNTED.equals(android.os.Environment
				.getExternalStorageState()))
			return null;
		String dir = Environment.getExternalStorageDirectory() + "/"
				+ Global.productName + "/Image/";
		File file = null;
		try {
			if (!new File(dir).exists()) {
				new File(dir).mkdirs();
			}
			file = new File(dir + name);
			if (file.exists()) {
				file.delete();
			}
			file.createNewFile();
			FileOutputStream fOut = new FileOutputStream(file);
			mBitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
			fOut.flush();
			fOut.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return file;
	}

	// 退出聊天室
	private void exiterGroup() {
		if (!isGroup)
			return;
		ALCCPEngine.defauleEngine().exitGroup(
				CustomApplication.getInstance().currgroup, new CallBack() {
					@Override
					public void done(Object object, AVException avexception) {
						MLog.i(TAG, "-exitGroup---object:" + object
								+ " avexception:" + avexception);
					}
				});
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		exiterGroup();
	}

	public void setGridViewHeightBasedOnChildren(GridView gridview) {
		ListAdapter listAdapter = gridview.getAdapter();
		if (listAdapter == null) {
			// pre-condition
			return;
		}

		int totalHeight = 0;
		for (int i = 0; i < listAdapter.getCount(); i++) {
			View listItem = listAdapter.getView(i, null, gridview);
			listItem.measure(0, 0);
			totalHeight += listItem.getMeasuredHeight();
		}

		ViewGroup.LayoutParams params = gridview.getLayoutParams();
		params.height = totalHeight / 3 + DensityUtil.dip2px(this, 40);
		gridview.setLayoutParams(params);
	}

	@Override
	protected void onPause() {
		super.onPause();
		// 更新界面消息为已读
		if (!isGroup)
			msgadpter.updateAllMessageDBToRead();
		// 发送广播告知messageFragment更新页面
		Intent intent = new Intent(
				CCPIntentUtils.INTENT_FRAGMENT_MESSAGE_UPDATE);
		sendBroadcast(intent);
	}

	@Override
	public void onBackPressed() {
		if (layout_more.getVisibility() == View.VISIBLE) {
			layout_more.setVisibility(View.GONE);
			return;
		}
		super.onBackPressed();

	}

	public void showContextMenu(int postion) {
		mlist.showContextMenu();
	}

	// listview长按菜单
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		IMChatMessage message = msgadpter
				.getItem(msgadpter.getLongclickindex());
		int type = message.getMessageType();

		if (type == IMChatMessage.MessageType.TXT) {
			menu.setHeaderTitle("菜单");
			menu.add(0, 1, 0, "复制");
			if(message.isTranflag()){
				menu.add(0, 2, 0, "原文");
			}else{
				menu.add(0, 3, 0, "翻译");
			}
		} else if (type == IMChatMessage.MessageType.IMAGE) {

		} else if (type == IMChatMessage.MessageType.VOICE) {

		} else if (type == IMChatMessage.MessageType.VIDEO) {

		} else if (type == IMChatMessage.MessageType.GROUPINVITE) {
			menu.setHeaderTitle("菜单");
			menu.add(0, 4, 0, "加入群组");
		}

	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		IMChatMessage message = msgadpter
				.getItem(msgadpter.getLongclickindex());
		switch (item.getItemId()) {
		case 1:// 复制
			ClipboardManager cmb = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
			cmb.setText(message.getMessageContent());
			showSysToast("复制成功");
			break;
		case 2: // 原文
			message.setTranflag(false);
			msgadpter.notifyDataSetChanged();
			break;
		case 3: // 翻译
			message.setTranflag(true);
			msgadpter.notifyDataSetChanged();
			break;
		case 4:// 加入群组
			try {
				AVObject group = AVObject.createWithoutData("Group",
						message.getMediaUrl());
				group.fetchIfNeededInBackground(new GetCallback<AVObject>() {

					@Override
					public void done(AVObject arg0, AVException arg1) {
						if (arg0 != null && arg1 == null) {
							CustomApplication.getInstance().currgroup = arg0;
							Intent intent = new Intent(GroupChatActivity.this,
									GroupChatActivity.class);
							intent.putExtra("titlename", arg0.getString("name"));
							intent.putExtra("isGroup", true);
							startActivity(intent);
							finish();
						} else {
							showSysToast("进入群失败");
						}
						if(arg1 != null)
							arg1.printStackTrace();
					}

				});
			} catch (Exception e) {
				e.printStackTrace();
				showSysToast("进入群失败");

			}
			break;

		default:
			break;
		}
		return super.onContextItemSelected(item);
	}

}
